<template>
  <a-layout id="components-layout-demo-top" class="layout">
    <a-layout-header>
      <div class="logo" />
    </a-layout-header>
    <a-layout-content style="padding: 0 50px">
      <div v-if="isExpired">
        <a-alert type="warning">
          <div slot="message">session已过期 请
            获取最新session <a href="http://tmsearch.uspto.gov" target="_blank">http://tmsearch.uspto.gov</a>
          </div>
        </a-alert>
      </div>
      <div v-if="isLoading" class="loading" style="text-align: center">
        <a-spin :tip="loadingTxt"></a-spin>
      </div>
      <div :style="{ background: '#fff', padding: '24px', minHeight: '280px' }">
        <div v-if="!isLoading && (this.resultArr.length || this.failArr.length)">查询完成</div>
        <div>
          <h2>配置</h2>
          查询时间 {{defaultSearchTime}}s(尽量更长时间)：
          <a-input @change="searchTimeChange" style="width: 50px" :value="defaultSearchTime"></a-input>
          <!--每次查询商标个数(默认{{defaultSearchNum}})：-->
          <!--<a-input @change="searchNumChange" style="width: 50px" :value="defaultSearchNum"></a-input>-->
        </div>
        <div>
          <a-upload name="file" :multiple="true" action="//jsonplaceholder.typicode.com/posts/" :headers="headers"
                    @change="handleChange">
            <a-button>
              <a-icon type="upload" />
              上传excel文件
            </a-button>
          </a-upload>
          <div>
            <h5>找到了{{downLoadData.length}}条数据,
              {{allBrand.length}}个商标,每个查询需要{{defaultSearchTime}}秒，
              查询所有大概需要{{getTime}}</h5>
            <div>
              <div style="max-height: 300px;overflow: auto;color: #d11ea9">
                {{allBrand.join(',')}}
              </div>
            </div>
          </div>
        </div>
        <a-divider></a-divider>
        <div>
          session:获取最新session <a href="http://tmsearch.uspto.gov" target="_blank">http://tmsearch.uspto.gov</a>
          <a-input placeholder="请输入session" :value="session" @change="inputChange"></a-input>
        </div>
        <div>
          查询的商标列表：(本次共查询{{getDownloadData.split(',').length}}个商标，每个查询需要{{defaultSearchTime}}秒，
          查询所有大概需要{{getSearchTime}})
          <a-textarea
            style="color: #3215c6"
            placeholder="请输入商标，逗号隔开"
            @change="areaChange"
            :value="getDownloadData"
            :autosize="{ minRows: 4, maxRows: 6 }" />
        </div>
        <div>
          <a-button type="primary" @click="handleSubmit">提交查询</a-button>
          <a-divider></a-divider>
          <a-button type="primary" @click="handleDownload">下载</a-button>

          <!--<a-button @click="handleReset">清除</a-button>-->
        </div>
        <div v-if="resultArr.length" style="color: green">
          无商标的列表：
          <ul>
            <li v-for="(item,index) in  resultArr" :key="item+index">{{item}}</li>
          </ul>
        </div>
        <div style="color: red">
          <p>失败的列表（可能是失败的，可能不是有商标的，多查一次）</p>
          {{failArr.join(',')}}
        </div>
      </div>
    </a-layout-content>
    <a-layout-footer style="text-align: center">
      Design ©2018 Created by <a href="http://www.liuweibo.cn/about" target="_blank">刘伟波</a>
    </a-layout-footer>
  </a-layout>
</template>
<style>
  .ant-spin-spinning {
    position: fixed;
    top: 50%;
    transform: translateY(-50%);
    z-index: 9999;
  }

  #components-layout-demo-top {
    min-height: 100%;
  }

  #components-layout-demo-top .logo {
    width: 120px;
    height: 31px;
    background: rgba(255, 255, 255, .2);
    margin: 16px 24px 16px 0;
    float: left;
  }
</style>

<script>
  import { getSSS } from './services/requests'
  import { importf } from './upload'
  import { downloadExl } from './download'
  export default {
    name: 'app',
    components: {},
    data () {
      return {
        resultArr: [],
        failArr: [],
        headers: {
          authorization: 'authorization-text'
        },
        defaultSearchTime: 3,
        defaultSearchNum: 500,
        downLoadData: [],
        percent: 0,
        isLoading: false,
        nextSeqid: 0,
        session: '4803%3Ar4rig.1.1',
        searchArrTxt: 'bestjoy,AUJOY,Chelzen,All Clad Textiles',
        txt: 'No TESS records were found to match the criteria of your query',
        expiredTxt: 'This search session has expired',
        isExpired: false
      }
    },
    computed: {
      getTime () {
        const allS = this.allBrand.length * this.defaultSearchTime
        return `${allS / 60}分钟`
      },
      getSearchTime () {
        const allS = this.getSearchArr.length * this.defaultSearchTime
        return `${allS / 60}分钟`
      },
      allBrand () {
        return [...new Set(this.downLoadData.map(v => this.getValue(v)))]
      },
      loadingTxt () {
        return this.percent + '%Loading...'
      },
      getDownloadData () {
        return this.searchArrTxt
      },
      getSearchArr () {
        const arr = this.searchArrTxt.replace(/，/g, ',')
          .split(',')
        return [...new Set(arr)]
      }
    },
    created () {
      const session = sessionStorage.getItem('session', this.session)
      if (session) this.session = session
    },
    watch: {
      percent (cur) {
        this.isLoading = cur != 100.00
      }
    },
    methods: {
      getKey () {
        return ' Brand' || 'Brand'
      },
      getValue (v) {
        return v[this.getKey()]
      },
      handleChange (info) {
        if (info.file.status !== 'uploading') {
          importf(info.file.originFileObj, this)
        }
      },
      searchNumChange (e) {
        this.defaultSearchNum = e.target.value
      },
      searchTimeChange (e) {
        this.defaultSearchTime = e.target.value
      },
      inputChange (e) {
        this.session = e.target.value
      },
      areaChange (e) {
        this.searchArrTxt = e.target.value
      },
      handleReset () {
        this.session = ''
        this.percent = 0
        this.resultArr = []
        this.searchArrTxt = ''
        this.nextSeqid = 0
      },
      sleep () {
        return new Promise((resolve) => {
          setTimeout(() => {
            resolve()
          }, this.defaultSearchTime * 1000)
        })
      },
      getExcelData (result, data) {
        let resultData = []
        result.forEach(item => {
          data.forEach(v => {
            if (item === v[' Brand']) {
              resultData.push(v)
            }
          })
        })
        return resultData
      },
      handleDownload () {
        // let result = ['4U LIFE ', 1000]
        // const data = [
        //   { 'ASIN': 'B01E512EZI ', ' Brand': 1000 },
        //   { 'ASIN': 'B01E512ERI ', ' Brand': 1000 }, {
        //     'ASIN': 'B07BFLYNNT ',
        //     ' Brand': 43755
        //   }, { 'ASIN': 'B0773YHNKR ', ' Brand': '4U LIFE ' }, {
        //     'ASIN': 'B01CXM1Z24 ',
        //     ' Brand': '4U LIFE '
        //   }, { 'ASIN': 'B01CXM1ZXS ', ' Brand': '4U LIFE ' }, {
        //     'ASIN': 'B06ZZY6JXR ',
        //     ' Brand': '4U LIFE '
        //   }]
        // console.log(this.getExcelData(result,data))
        if (this.resultArr.length && this.downLoadData.length) {
          downloadExl(this.getExcelData(this.resultArr, this.downLoadData))
        }
      },
      async handleSubmit () {
        this.nextSeqid = 0
        this.percent = 0
        this.failArr = []
        this.isLoading = true
        this.session && sessionStorage.setItem('session', this.session)
        this.resultArr = []
        const arr = this.getSearchArr
        if (arr.length === 0 || this.session === '') {
          alert('请输入session和word')
          return
        }
        for (let i = 0; i < arr.length; i++) {
          const word = arr[i]
          this.nextSeqid++
          if (this.nextSeqid !== 1) await this.sleep()
          await getSSS(word, this.session)
            .then(res => {
              if (res.data.indexOf(this.expiredTxt) === -1) {
                if (res.data.indexOf(this.txt) !== -1) {
                  this.resultArr.push(word)
                }
                this.isExpired = false
              } else {
                this.isExpired = true
              }
            })
            .catch(err => {
              this.failArr.push(word)
              console.log(err)
            })
          this.percent = ((this.nextSeqid) / (this.getSearchArr.length) * 100).toFixed(2)
        }
      }
    }
  }
</script>

